<template>
  <div class="materialConfig-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="编码" prop="number">
          <el-input
            placeholder="请输入编码"
            v-model="searchForm.number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            placeholder="请输入名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="物料类型" prop="materialTypeNumber">
          <el-select
            style="width: 220px"
            v-model="searchForm.materialTypeNumber"
            placeholder="选择物料类型"
          >
            <el-option
              v-for="option in materialCategoryList"
              :key="option.materialTypeNumber"
              :label="option.materialTypeName"
              :value="option.materialTypeNumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-select
            style="width: 220px"
            v-model="searchForm.enabled"
            placeholder="选择状态"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增物料配置
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click.prevent="showBatchDeleteDialog"
        >
          批量删除
        </el-button>
        <el-button
          style="width: 80px"
          type="warning"
          @click.prevent="showImportDialog"
        >
          导入
        </el-button>
        <el-button
          style="width: 80px"
          type="success"
          @click.prevent="showExportDialog"
        >
          导出
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="number" label="编码" width="100" />
          <el-table-column prop="name" label="名称" width="220" />
          <el-table-column
            prop="materialTypeName"
            label="物料类型"
            width="140"
          />
          <el-table-column prop="unitName" label="单位" width="60" />
          <el-table-column
            prop="relationCount"
            label="关联原物料"
            width="100"
          />
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="scope">
              <el-tag
                :type="scope.row.enabled === 0 ? 'success' : 'danger'"
                disable-transitions
              >
                {{ scope.row.enabled === 0 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="190" />
          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scope">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.enabled == 0"
                type="danger"
                size="small"
                @click.prevent="showEnabledDialog(scope.row, 2)"
                >禁用</el-button
              >
              <el-button
                v-else
                type="success"
                size="small"
                @click.prevent="showEnabledDialog(scope.row, 2)"
                >启用</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <MaterialConfigAddUpdate v-model="addUpdateRef"></MaterialConfigAddUpdate>
    <MaterialConfigRemove v-model="removeRef"></MaterialConfigRemove>
    <MaterialConfigImport v-model="importRef"></MaterialConfigImport>
    <MaterialConfigEnable v-model="enabledRef"></MaterialConfigEnable>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getMaterialConfigAllList,
  getMaterialConfigPagination,
} from '@/api/fms-material-config.api'
import { getMaterialCategoryAllList } from '@/api/fms-material-category.api'
import { getMaterialUnitAllList } from '@/api/fms-material-unit.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCanUseCode } from '@/api/fms-code-dict.api'
// import { useUserPermission } from "@/utils/permission.utils";
import MaterialConfigRemove from './MaterialConfigRemove.vue'
import MaterialConfigAddUpdate from './MaterialConfigAddUpdate.vue'
import MaterialConfigImport from './MaterialConfigImport.vue'
import { statusOptions } from '@/utils/common.utils'
import {
  batchRemoveMaterialConfig,
  downloadMaterialConfig,
} from '@/api/fms-material-config.api'
import MaterialConfigEnable from './MaterialConfigEnable.vue'

//获取从父组件传来的数据。
const props = defineProps(['modelValue'])
// const userPermission = useUserPermission();

const requestCanUseCode = () => {
  getCanUseCode({ type: 5 })
    .then((res: any) => {
      console.log('getCanUseCode: ', res)
      addUpdateRef.form.number = res
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

const enabledRef = reactive({
  visible: false,
  form: {
    id: '',
    enabled: '',
  },
  refreshDataList: () => {
    getDataList()
  },
})

const showEnabledDialog = (item: any) => {
  enabledRef.visible = true
  enabledRef.form.id = item.id
  enabledRef.form.enabled = item.enabled ? '0' : '1'
}

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `物料配置`,
  curSelectRow: {},
  materialCategoryList: [] as any[],
  materialUnitList: [] as any[],
  form: {} as any,
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

const importRef = reactive({
  visible: false,
  title: '导入物料配置',
  curSelectRow: {},
  form: {},
  refreshDataList: () => {
    getDataList()
  },
})

const showImportDialog = () => {
  console.log('showImportDialog')
  importRef.visible = true
  importRef.title = '导入物料配置'
  importRef.form = {
    fileList: [],
  }
}

function getCurrentTimeString() {
  const now = new Date()
  const year = now.getFullYear() // 4位年份（如2025）
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份（0-11，需+1）
  const day = String(now.getDate()).padStart(2, '0') // 日期（1-31）
  const hours = String(now.getHours()).padStart(2, '0') // 24小时制小时（0-23）
  const minutes = String(now.getMinutes()).padStart(2, '0') // 分钟（0-59）
  const seconds = String(now.getSeconds()).padStart(2, '0') // 秒（0-59）
  return `${year}${month}${day}${hours}${minutes}${seconds}` // 组合成字符串
}

const showExportDialog = () => {
  downloadMaterialConfig()
    .then((res: any) => {
      // 2. 创建Blob对象（指定Excel MIME类型）
      const blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })

      // 3. 创建临时下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute(
        'download',
        `物料导出列表_${getCurrentTimeString()}.xlsx`
      ) // 设置文件名

      // 4. 模拟点击下载
      document.body.appendChild(link)
      link.click()

      // 5. 清理资源
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url) // 释放Blob URL内存
    })
    .catch((err) => {
      console.log('downloadMaterialConfig error: ', err)
    })
  console.log('showExportDialog')
}

const showAddEditDialog = (item: any, type: number) => {
  //新增 物料配置
  if (item.target) {
    let form = {
      id: null,
      number: '',
      name: '',
      unitId: '',

      //常温保质期
      expirationDate: 1,
      //冷藏保质期
      freezeExpirationDate: 1,
      //清洗周期
      disinfectCycle: 1,

      //强制报废
      forceThrow: 2,
      //强制清洗
      forceDisinfect: 2,
      //始终单独出料
      alwaysDischargeSeparately: 2,
      //强制扫码补料
      forcedScanning: 2,
      //为性状易受影响物料
      sticky: 2,
      //是否启动
      enabled: '0',
      //1份物料
      portion: 1,
      //是否支持萃取
      extracted: 2,

      liquidityCoefficient: '',
      unitName: '',
      materialTypeId: '',
      relationCount: '',
      srcMaterialId: '',
      materialConversionCoefficient: '',
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    number: item.number,
    name: item.name,
    unitId: item.unitId,
    sticky: item.sticky,
    disinfectCycle: item.disinfectCycle,
    forceThrow: item.forceThrow,
    forceDisinfect: item.forceDisinfect,
    liquidityCoefficient: item.liquidityCoefficient,
    materialTypeId: item.materialTypeId,
    unitName: item.unitName,
    materialTypeName: item.materialTypeName,
    relationCount: item.relationCount,
    enabled: item.enabled,
    expirationDate: item.expirationDate,
    freezeExpirationDate: item.freezeExpirationDate,
    srcMaterialId: item.srcMaterialId,
    alwaysDischargeSeparately: item.alwaysDischargeSeparately,
    forcedScanning: item.forcedScanning,
    materialConversionCoefficient: item.materialConversionCoefficient,
    portion: item.portion,
    extracted: item.extracted,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: '物料配置',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 批量删除操作 =====================
 */
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const showBatchDeleteDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条物料配置数据吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      batchDeleteMaterialConfigs()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const batchDeleteMaterialConfigs = () => {
  const ids = selectedRows.value.map((row: any) => row.id)
  batchRemoveMaterialConfig([...ids])
    .then((res) => {
      ElMessage({
        message: `删除成功`,
        type: 'success',
      })

      getDataList()
    })
    .catch((err) => {
      ElMessage({
        message: err.msg || err,
        type: 'error',
      })
    })
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  number: '',
  name: '',
  unitNumber: '',
  sticky: '',
  disinfectCycle: '',
  forceThrow: 2,
  forceDisinfect: 2,
  liquidityCoefficient: '',
  materialTypeNumber: '',
  unitName: '',
  materialTypeName: '',
  relationCount: '',
  enabled: '',
  createTime: '',
  expirationDate: '',
  freezeExpirationDate: '',
  srcMaterialId: '',
  alwaysDischargeSeparately: '',
  forcedScanning: '',
  materialConversionCoefficient: '',
  portion: '',
  extracted: '',
})

const tableLoading = ref(false)
const tableData = ref([])
const selectedRows = ref<any[]>([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let unitNumber = searchForm.value.unitNumber
  if (unitNumber) {
    searchCondition.unitNumber = unitNumber
  }
  let sticky = searchForm.value.sticky
  if (sticky) {
    searchCondition.sticky = sticky
  }
  let disinfectCycle = searchForm.value.disinfectCycle
  if (disinfectCycle) {
    searchCondition.disinfectCycle = disinfectCycle
  }
  let forceThrow = searchForm.value.forceThrow
  if (forceThrow) {
    searchCondition.forceThrow = forceThrow
  }
  let forceDisinfect = searchForm.value.forceDisinfect
  if (forceDisinfect) {
    searchCondition.forceDisinfect = forceDisinfect
  }
  let liquidityCoefficient = searchForm.value.liquidityCoefficient
  if (liquidityCoefficient) {
    searchCondition.liquidityCoefficient = liquidityCoefficient
  }
  let materialTypeNumber = searchForm.value.materialTypeNumber
  if (materialTypeNumber) {
    searchCondition.materialTypeNumber = materialTypeNumber
  }
  let unitName = searchForm.value.unitName
  if (unitName) {
    searchCondition.unitName = unitName
  }
  let materialTypeName = searchForm.value.materialTypeName
  if (materialTypeName) {
    searchCondition.materialTypeName = materialTypeName
  }
  let relationCount = searchForm.value.relationCount
  if (relationCount) {
    searchCondition.relationCount = relationCount
  }
  let enabled = searchForm.value.enabled
  if (enabled) {
    searchCondition.enabled = enabled
  }
  let createTime = searchForm.value.createTime
  if (createTime) {
    searchCondition.createTime = createTime
  }
  let expirationDate = searchForm.value.expirationDate
  if (expirationDate) {
    searchCondition.expirationDate = expirationDate
  }
  let freezeExpirationDate = searchForm.value.freezeExpirationDate
  if (freezeExpirationDate) {
    searchCondition.freezeExpirationDate = freezeExpirationDate
  }
  let srcMaterialId = searchForm.value.srcMaterialId
  if (srcMaterialId) {
    searchCondition.srcMaterialId = srcMaterialId
  }
  let alwaysDischargeSeparately = searchForm.value.alwaysDischargeSeparately
  if (alwaysDischargeSeparately) {
    searchCondition.alwaysDischargeSeparately = alwaysDischargeSeparately
  }
  let forcedScanning = searchForm.value.forcedScanning
  if (forcedScanning) {
    searchCondition.forcedScanning = forcedScanning
  }
  let materialConversionCoefficient =
    searchForm.value.materialConversionCoefficient
  if (materialConversionCoefficient) {
    searchCondition.materialConversionCoefficient =
      materialConversionCoefficient
  }
  let portion = searchForm.value.portion
  if (portion) {
    searchCondition.portion = portion
  }
  let extracted = searchForm.value.extracted
  if (extracted) {
    searchCondition.extracted = extracted
  }

  tableLoading.value = true
  getMaterialConfigPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const materialCategoryList = ref<any[]>([])
const requestMaterialCategoryList = () => {
  getMaterialCategoryAllList({}).then(function (res: any) {
    console.log('getMaterialCategoryAllList: ', res)
    materialCategoryList.value = res || []
    addUpdateRef.materialCategoryList = materialCategoryList.value
  })
}

const materialUnitList = ref<any[]>([])
const requestMaterialUnitAllList = () => {
  getMaterialUnitAllList({}).then(function (res: any) {
    console.log('getMaterialUnitAllList: ', res)
    materialUnitList.value = res || []
    addUpdateRef.materialUnitList = materialUnitList.value
  })
}

onMounted(() => {
  requestMaterialCategoryList()
  requestMaterialUnitAllList()
  getDataList()
})
</script>
<style lang="scss" scoped>
.materialConfig-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.materialConfig-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
